package com.ohuang.jiaxiaotong.Activity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.ohuang.jiaxiaotong.MyHttpURL;
import com.ohuang.jiaxiaotong.R;
import com.ohuang.jiaxiaotong.Util.Ohuang;
import com.ohuang.jiaxiaotong.Util.Sys;
import com.ohuang.jiaxiaotong.base.BaseAc;
import com.ohuang.jiaxiaotong.entity.ParentMsg;
import com.ohuang.jiaxiaotong.entity.TeacherMsg;

import java.util.HashMap;
import java.util.Objects;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.POST;
import retrofit2.http.QueryMap;

public class UserMsgActivity extends BaseAc {
    private String username, role;
    private TextView textView_username, textView_child, textView_introduce, textView_phone,textView_name;
    private Button button_sendMsg;
    private ImageView imageView_bg, imageView_icon;
    private View view_bg, view_0, view_1;
    private static final int READ_REQUEST_CODE = 42;
    private String iconUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_msg);
        setTitle("个人资料");
        Ohuang.changeStatusBarTextImgColor(this, true);
        Objects.requireNonNull(getSupportActionBar()).setHomeAsUpIndicator(R.mipmap.icon_goback);//设置ActionBar返回按钮

        Intent intent = getIntent();
        username = intent.getStringExtra("username");
        role = intent.getStringExtra("role");
        iconUrl=intent.getStringExtra("iconUrl");
        initView();
        if ("0".equals(role)) {
            view_1.setVisibility(View.GONE);
            HttpGetTeacher();
        } else {
            view_0.setVisibility(View.GONE);
            HttpGetParent();
        }
    }

    private void initView() {
        textView_child = findViewById(R.id.txt_child_userMsg);
        textView_username = findViewById(R.id.txt_username_userMsg);
        textView_name=findViewById(R.id.txt_name_userMsg);
        textView_introduce = findViewById(R.id.txt_introduce_userMsg);
        textView_phone = findViewById(R.id.txt_phone_userMsg);
        button_sendMsg = findViewById(R.id.btn_sendMsg_userMsg);
        view_bg = findViewById(R.id.view_setBG_userMsg);
        view_0 = findViewById(R.id.layout_0_UserMsg);
        view_1 = findViewById(R.id.layout_1_UserMsg);
        imageView_bg = findViewById(R.id.img_bg_userMsg);
        imageView_icon = findViewById(R.id.img_icon_userMsg);
        textView_username.setText(username);
        String stringUri = Sys.ReadSharedPer(this, "bgUri", "");
        if (stringUri.isEmpty()) {
            //背景
            Glide.with(this).load(R.drawable.img_bg)
                    .into(imageView_bg);
        } else {
            //背景
            Uri uri = Uri.parse(stringUri);
            Glide.with(this).load(uri).error(R.drawable.img_bg).into(imageView_bg);
        }
        view_bg.setOnClickListener(new View.OnClickListener() {//点击头像上方 选择图片
            @Override
            public void onClick(View v) {
                if (Sys.isClick()) {
                    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);

                    intent.addCategory(Intent.CATEGORY_OPENABLE);

                    intent.setType("image/*");

                    startActivityForResult(intent, READ_REQUEST_CODE);
                }
            }
        });

        button_sendMsg.setOnClickListener(v -> {
            if (Sys.isClick()) {
                Intent intent = new Intent(UserMsgActivity.this, ChatActivity.class);
                intent.putExtra("username", username);
                startActivity(intent);
            }
        });

        Glide.with(UserMsgActivity.this).load(iconUrl)
                .error(R.drawable.img_icon)
                .fallback(R.drawable.img_icon)
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                .into(imageView_icon);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode,
                                 Intent resultData) {

        // The ACTION_OPEN_DOCUMENT intent was sent with the request code
        // READ_REQUEST_CODE. If the request code seen here doesn't match, it's the
        // response to some other intent, and the code below shouldn't run at all.

        super.onActivityResult(requestCode, resultCode, resultData);
        if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            // The document selected by the user won't be returned in the intent.
            // Instead, a URI to that document will be contained in the return intent
            // provided to this method as a parameter.
            // Pull that URI using resultData.getData().
            Uri uri = null;
            if (resultData != null) {
                uri = resultData.getData();
                System.out.println(uri);
                Glide.with(this).load(uri)

                        .into(imageView_bg);

                Sys.WriteSharedPer(this, "bgUri", uri.toString());
            }
        }
    }

    private void HttpGetTeacher() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(MyHttpURL.mainUrl + "user/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        GithubService service = retrofit.create(GithubService.class);
        HashMap<String, String> map = new HashMap<>();
        map.put("username", username);
        service.getTeacher(map).enqueue(new Callback<TeacherMsg>() {
            @Override
            public void onResponse(Call<TeacherMsg> call, Response<TeacherMsg> response) {
                textView_name.setText(response.body().getTeacherName());
                textView_introduce.setText(response.body().getIntro());
                textView_phone.setText(response.body().getIphone());
            }

            @Override
            public void onFailure(Call<TeacherMsg> call, Throwable t) {

            }
        });
    }

    private void HttpGetParent() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(MyHttpURL.mainUrl + "user/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        GithubService service = retrofit.create(GithubService.class);
        HashMap<String, String> map = new HashMap<>();
        map.put("username", username);
        service.getParent(map).enqueue(new Callback<ParentMsg>() {
            @Override
            public void onResponse(Call<ParentMsg> call, Response<ParentMsg> response) {
                textView_name.setText(response.body().getParentName());
                textView_child.setText(response.body().getChildName());
                textView_phone.setText(response.body().getIphone());

            }

            @Override
            public void onFailure(Call<ParentMsg> call, Throwable t) {

            }
        });

    }

    interface GithubService {
        //https://api.github.com/repos/{owner}/{repo}/contributors
        @POST("findTeacherMsg")
        Call<TeacherMsg> getTeacher(@QueryMap HashMap<String, String> deviceInfo);

        @POST("findParentMsg")
        Call<ParentMsg> getParent(@QueryMap HashMap<String, String> deviceInfo);
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        if (item.getItemId() == android.R.id.home) {//左上角返回按钮
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
